package datastructure.sort;

import java.util.Arrays;

/**
 * 冒泡排序 O(n^2)
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-24
 */
public class BubbleSort {

    public static void main(String[] args) {
        BubbleSort bubbleSort = new BubbleSort();
        int[] array = new int[]{5, 1, 9, -1, 4, 0};
        long startTime = System.currentTimeMillis();
        bubbleSort.bubbleSort(array);
        long endTime = System.currentTimeMillis();
        System.out.println(Arrays.toString(array));
        System.out.println("耗时：" + (endTime - startTime));
    }

    /**
     * 冒泡排序
     *
     * @param array
     */
    public void bubbleSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            int temp;
            // 优化标志
            boolean flg = false;
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    flg = true;
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
            System.out.println("第" + i + "次排序: " + Arrays.toString(array));
            // 如果没有交换顺序 说明已经是有序的了
            if (!flg) {
                break;
            }
        }
    }
}
